package com.kkd.kkdapp.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.http.entity.MonthTabsItem;
import com.kkd.kkdapp.utils.SystemUtils;

public class CategoryTabStrip extends HorizontalScrollView {
	private LayoutInflater mLayoutInflater;
	private LinearLayout tabsContainer;
	private int tabCount;

	private int currentPosition = 0;
	private float currentPositionOffset = 0f;

	private Rect indicatorRect;
	private Rect rect_line;

	private LinearLayout.LayoutParams defaultTabLayoutParams;

	private int scrollOffset = 10;
	private int lastScrollX = 0;

	private Drawable indicator;
	private TextDrawable[] drawables;
	private Drawable left_edge;
	private Drawable right_edge;

	public CategoryTabStrip(Context context) {
		this(context, null);
	}

	public CategoryTabStrip(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public CategoryTabStrip(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		mLayoutInflater = LayoutInflater.from(context);
		drawables = new TextDrawable[3];
		int i = 0;
		while (i < drawables.length) {
			drawables[i] = new TextDrawable(getContext());
			i++;
		}

		indicatorRect = new Rect();
		rect_line = new Rect();
		setFillViewport(true);
		setWillNotDraw(false);

		tabsContainer = new LinearLayout(context);
		tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
		tabsContainer.setLayoutParams(new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		addView(tabsContainer);

		DisplayMetrics dm = getResources().getDisplayMetrics();
		// scrollOffset = (int) TypedValue.applyDimension(
		// TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
		scrollOffset = (int) (SystemUtils.getScreenWidth(getContext()) / 2 - SystemUtils
				.getScreenWidth(getContext()) / 10);
		defaultTabLayoutParams = new LinearLayout.LayoutParams(
				(int) (SystemUtils.getScreenWidth(getContext()) / 5),
				LayoutParams.MATCH_PARENT);

		// 绘制高亮区域作为滑动分页指示器
		indicator = getResources()
				.getDrawable(R.drawable.bg_category_indicator);
		// 左右边界阴影效果
		left_edge = getResources()
				.getDrawable(R.drawable.ic_category_left_edge);
		right_edge = getResources().getDrawable(
				R.drawable.ic_category_right_edge);
	}

	private KCalendar mKCalendar;
	private List<MonthTabsItem> list_date = new ArrayList<MonthTabsItem>();

	/**
	 * 设置需要显示的月份数据源
	 */
	public void setKcalendarAndDate(KCalendar kCalendar,
			List<MonthTabsItem> list) {
		mKCalendar = kCalendar;
		list_date = list;
		notifyDataSetChanged();
	}

	// 当附加在Tabs的数据发生变化时,应该调用该方法通知CategoryTabStrip刷新数据
	public void notifyDataSetChanged() {
		tabsContainer.removeAllViews();

		tabCount = list_date.size();

		for (int i = 0; i < tabCount; i++) {
			addTab(i,
					list_date
							.get(i)
							.getMonthString()
							.substring(
									list_date.get(i).getMonthString()
											.lastIndexOf("-") + 1)
							+ "月");
		}

	}

	private void addTab(final int position, String title) {
		ViewGroup tab = (ViewGroup) mLayoutInflater.inflate(
				R.layout.category_tab, this, false);
		TextView category_text = (TextView) tab
				.findViewById(R.id.category_text);
		ImageView flag = (ImageView) tab.findViewById(R.id.flag);
		if (list_date.get(position).isHaveTip()) {
			flag.setVisibility(View.VISIBLE);
		} else {
			flag.setVisibility(View.GONE);
		}
		String noZeroTitle = "";
		if (!TextUtils.isEmpty(title) && title.startsWith("0")) {
			noZeroTitle = title.replace("0", "");
		} else {
			noZeroTitle = title;
		}
		category_text.setText(noZeroTitle);
		category_text.setGravity(Gravity.CENTER);
		category_text.setSingleLine();
		category_text.setFocusable(true);
		category_text.setTextColor(Color.parseColor("#666666"));
		tab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String dateString = list_date.get(position).getMonthString();
				int index_line = dateString.indexOf("-");
				mKCalendar.setYearAndMonth(
						Integer.parseInt(dateString.substring(0, index_line)),
						Integer.parseInt(dateString.substring(index_line + 1)));
			}
		});

		tabsContainer.addView(tab, position, defaultTabLayoutParams);
	}

	// 计算滑动过程中矩形高亮区域的上下左右位置
	private void calculateIndicatorRect(Rect rect) {
		ViewGroup currentTab = (ViewGroup) tabsContainer
				.getChildAt(currentPosition);

		float left = (float) (currentTab.getLeft());
		float width = ((float) currentTab.getWidth()) + left;

		if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
			ViewGroup nextTab = (ViewGroup) tabsContainer
					.getChildAt(currentPosition + 1);

			float next_left = (float) (nextTab.getLeft());
			left = left * (1.0f - currentPositionOffset) + next_left
					* currentPositionOffset;
			width = width * (1.0f - currentPositionOffset)
					+ currentPositionOffset
					* (((float) nextTab.getWidth()) + next_left);
		}

		rect.set(((int) left) + getPaddingLeft(),
				getPaddingTop() + currentTab.getTop(), ((int) width)
						+ getPaddingLeft(), currentTab.getTop()
						+ getPaddingTop() + currentTab.getHeight());
	}

	// 计算滚动范围
	private int getScrollRange() {
		return getChildCount() > 0 ? Math.max(0, getChildAt(0).getWidth()
				- getWidth() + getPaddingLeft() + getPaddingRight()) : 0;
	}

	private void scrollToChild(int position, int offset) {

		if (tabCount == 0) {
			return;
		}

		calculateIndicatorRect(indicatorRect);

		int newScrollX = lastScrollX;
		if (indicatorRect.left < getScrollX() + scrollOffset) {
			newScrollX = indicatorRect.left - scrollOffset;
		} else if (indicatorRect.right > getScrollX() + getWidth()
				- scrollOffset) {
			newScrollX = indicatorRect.right - getWidth() + scrollOffset;
		}

		if (newScrollX != lastScrollX) {
			lastScrollX = newScrollX;
			scrollTo(newScrollX, 0);
		}
	}

	@Override
	public void draw(Canvas canvas) {
		super.draw(canvas);

		calculateIndicatorRect(indicatorRect);

		if (indicator != null) {
			rect_line.set(indicatorRect.left, indicatorRect.bottom
					- SystemUtils.dip2px(getContext(), 1.5f),
					indicatorRect.right, indicatorRect.bottom);
			indicator.setBounds(rect_line);
			indicator.draw(canvas);
		}

		int i = 0;
		while (i < tabsContainer.getChildCount()) {
			// 改变选中tab的文字颜色
			ViewGroup tab = (ViewGroup) tabsContainer.getChildAt(i);
			if (tab != null) {
				TextView category_text = (TextView) tab
						.findViewById(R.id.category_text);
				if (category_text != null) {
					if (i == currentPosition) {
						category_text.setTextColor(Color.parseColor("#5451B1"));
					} else {
						category_text.setTextColor(Color.parseColor("#666666"));
					}
				}
			}
			i++;
			// 此处注释掉部分为旧改变选择tab文字颜色逻辑
			// if (i < currentPosition - 1 || i > currentPosition + 1) {
			// i++;
			// } else {
			// ViewGroup tab = (ViewGroup) tabsContainer.getChildAt(i);
			// TextView category_text = (TextView) tab
			// .findViewById(R.id.category_text);
			// if (category_text != null) {
			// TextDrawable textDrawable = drawables[i - currentPosition
			// + 1];
			// int save = canvas.save();
			// calculateIndicatorRect(indicatorRect);
			// canvas.clipRect(indicatorRect);
			// textDrawable.setText(category_text.getText());
			// textDrawable.setTextSize(0, category_text.getTextSize());
			// textDrawable.setTextColor(Color.parseColor("#5451b1"));
			// int left = tab.getLeft()
			// + category_text.getLeft()
			// + (category_text.getWidth() - textDrawable
			// .getIntrinsicWidth()) / 2
			// + getPaddingLeft();
			// int top = tab.getTop()
			// + category_text.getTop()
			// + (category_text.getHeight() - textDrawable
			// .getIntrinsicHeight()) / 2
			// + getPaddingTop();
			// textDrawable.setBounds(left, top,
			// textDrawable.getIntrinsicWidth() + left,
			// textDrawable.getIntrinsicHeight() + top);
			// textDrawable.draw(canvas);
			// canvas.restoreToCount(save);
			// }
			// i++;
			// }
		}

		i = canvas.save();
		int top = getScrollX();
		int height = getHeight();
		int width = getWidth();
		canvas.translate((float) top, 0.0f);
		if (left_edge == null || top <= 0) {
			if (right_edge == null || top > getScrollRange()) {
				canvas.restoreToCount(i);
			}
			right_edge.setBounds(width - right_edge.getIntrinsicWidth(), 0,
					width, height);
			right_edge.draw(canvas);
			canvas.restoreToCount(i);
		}
		left_edge.setBounds(0, 0, left_edge.getIntrinsicWidth(), height);
		left_edge.draw(canvas);
		if (right_edge == null || top > getScrollRange()) {
			canvas.restoreToCount(i);
		}
		right_edge.setBounds(width - right_edge.getIntrinsicWidth(), 0, width,
				height);
		right_edge.draw(canvas);
		canvas.restoreToCount(i);
	}

	public void setCurTabs(int position) {
		currentPosition = position;
		currentPositionOffset = 0;
		scrollToChild(position, (int) (0 * tabsContainer.getChildAt(position)
				.getWidth()));
		invalidate();
	}

}
